package com.odin.rmsservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.odin.rmsservice.entity.User;
import com.odin.rmsservice.mapper.UserMapper;
import com.odin.rmsservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 用户服务接口实现类
 * @Author ICE
 * @Date 2018-11-10
 **/
@Slf4j
@CacheConfig(cacheNames = {"user"})
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public IPage<User> page(IPage<User> page, Wrapper<User> queryWrapper) {
        IPage<User> iPage = baseMapper.selectPage(page, queryWrapper);
        return iPage;
    }

    /**
     * 判断用户是否存在1条
     */
    @Override
    public User getOne(String username, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username)
                .eq("password", password));
        if (user != null) {
            log.info("找到目标用户：" + user);
            return user;
        } else {
            log.info("该用户不存在，核对账号密码： [username=" + username + ",password=" + password + "]");
            return null;
        }
    }

    @Override
    public User selectOne(String column, String value) {
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq(column, value));
        return user;
    }

    @Override
    public User getUserById(Long id) {
        log.info("根据id= " + id + "，查询用户信息，并写入缓存{user}，key=id");
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        log.info("更新用户信息，并更新缓存");
        saveOrUpdate(user);
    }

    @Override
    public void deleteUser(Long id) {
        log.info("删除id= " + id + "的用户，并清除缓存");
        removeById(id);
    }
}
